package org.shadow.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class NetworkClassLoader extends ClassLoader {

	private String url;

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		byte[] classData = getClassData(name);
		if (null == classData) {
			throw new ClassNotFoundException(name);
		}
		return defineClass(name, classData, 0, classData.length);
	}

	private byte[] getClassData(String className) {
		String classUrl = url + "/" + className.replace(".", "/") + ".class";
		try {
			URL url = new URL(classUrl);
			InputStream inputStream = url.openStream();
			int bufferLen = 1024;
			byte[] buffer = new byte[bufferLen];
			int len = 0;
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			while ((len = inputStream.read(buffer, 0, bufferLen)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			inputStream.close();
			byte[] classData = outputStream.toByteArray();
			outputStream.close();
			return classData;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
}
